from django.http import JsonResponse

from django.views import View

from ihome_project.apps.utils.views import LoginRequiredMixin



from django.shortcuts import render

# Create your views here.
import re, json
from django import http
from django.views import View
from django_redis import get_redis_connection
from django.contrib.auth import login, authenticate,logout

from users.models import User


class RegisterView(View):
    '''注册'''

    def post(self, request):
        # 注册用户
        # 接收参数
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        phonecode = json_dict.get('phonecode')
        password = json_dict.get('password')
        # 整体检验
        if not all([mobile, phonecode, password]):
            return JsonResponse({'errno': '4103',
                                 'errmsg': '参数错误'})
        # mobile格式检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': '4103',
                                 'errmsg': '参数错误'})
        # password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'errno': '4103',
                                 'errmsg': '参数错误'})
        # phonecode检验
        # 链接数据库
        redis_conn = get_redis_connection('verify_code')
        # 数据库中获取验证码
        phonecode_server = redis_conn.get('sms_%s' % mobile)
        # 判断验证码是否存在
        if not phonecode:
            return JsonResponse({'errno': '4002',
                                 'errmsg': '无数据'})
        # 对比数据库中的验证码是否和前端一致
        if phonecode != phonecode_server.decode():
            return JsonResponse({'errno': '4003',
                                 'errmsg': '数据错误'})
        # 保存到数据库
        try:
            user = User.objects.create_user(
                username=mobile,
                mobile=mobile,
                password=password)
        except Exception as e:
            return JsonResponse({'errno': '4302',
                                 'errmsg': '文件读写错误'})
        # 状态保持
        login(request, user)
        return JsonResponse({'errno': '0',
                             'errmsg': 'ok'})
class LoginView(View):
    """登录类试图"""

    def post(self, request):
        """登录接口"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')
        # 整体检验
        if not all([mobile, password]):
            return JsonResponse({'errno': '4103',
                                 'errmsg': '参数错误'})
        # 判断是否能登录
        user = authenticate(username=mobile,
                            password=password)

        # 判断是否为空，如果为空，返回
        if user is None:
            return JsonResponse({'errno': '4104',
                                 'errmsg': '用户不存在或存在未激活'})
        # 状态保持
        login(request, user)
        # 生成响应对象
        response = JsonResponse({'errno': '0',
                                 'errmsg': '登录成功'})
        # # 在响应中设置用户名信息
        response.set_cookie('username',
                            user.username,
                            max_age=3600 * 24 * 14)
        # 返回响应结果
        return response

    def delete(self,request):
        #退出登陆
        logout(request)
        response = JsonResponse({'errno': 0,
                                 'errmsg': '登录成功'})
        #清除cookie信息
        response.delete_cookie('username')

        return response

    def get(self,request):
        if request.user.is_authenticated:
            # print('name:',request.user.username)
            return JsonResponse({
                        'errno':'0',
                        'errmsg':'已登录',
                        'data':{
                            'user_id':request.user.id,
                            'name':request.user.username
                        }})
        else:
            return JsonResponse({
                'errno': 4101,
                'errmsg': '未登录'
            })




